package com.client;

import com.grpc.HelloProto;
import com.grpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.TimeUnit;

/**
 * 双向流式rpc
 */
public class BiDirectionStreamGrpcClient {

    public static void main(String[] args) {
        ManagedChannelBuilder<?> localhost = ManagedChannelBuilder.forAddress("localhost", 9000);
        ManagedChannel channel = localhost.usePlaintext().build();
        try {
            HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(channel);
            StreamObserver<HelloProto.HelloRequest> helloRequestStreamObserver = helloServiceStub.cs2ss(new StreamObserver<HelloProto.HelloResponse>() {

                public void onNext(HelloProto.HelloResponse value) {
                    System.out.println("客户端接受到响应 value = " + value.getResult());
                }

                public void onError(Throwable t) {
                    System.out.println("客户端接受到响应端 onError 事件");
                }

                public void onCompleted() {
                    System.out.println("客户端接受到响应端 onCompleted 事件");
                }
            });

            for (int i = 0; i < 9; i++) {
                HelloProto.HelloRequest helloRequest = HelloProto.HelloRequest.newBuilder()
                        .setName("宋江" + i)
                        .build();
                helloRequestStreamObserver.onNext(helloRequest);
                try {TimeUnit.SECONDS.sleep(1);}catch (Exception e){e.printStackTrace();}
            }
            helloRequestStreamObserver.onCompleted();
            channel.awaitTermination(15, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.shutdown();
        }
    }
}
